import defaultSettings from '@/settings'

const title = defaultSettings.title || 'Vue Admin Template'

export default function getPageTitle(pageTitle) {
  if (pageTitle) {
    return `${pageTitle} - ${title}`
  }
  return `${title}`
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

// 分组
export function groupBy(list, fn) {
  const groups = {}
  list.forEach(function(o) {
    const group = JSON.stringify(fn(o))
    groups[group] = groups[group] || []
    groups[group].push(o)
  })
  return groups
}

// 第几周 a年 b月 c日
export function getMonthWeek(a, b, c) {
  const date = new Date(a, parseInt(b) - 1, c)
  let w = date.getDay()
  const d = date.getDate()
  if (w === 0) {
    w = 7
  }
  var config = {
    getMonth: date.getMonth() + 1,
    getYear: date.getFullYear(),
    getWeek: Math.ceil((d + 6 - w) / 7)
  }
  return config
}
//
export function uuid() {
// return (+new Date() * 1e6 + Math.floor(Math.random() * 1e6)).toString(36);
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0
    var v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

//
export function clone(obj) {
  let result = ''
  //
  if (typeof obj === 'object') {
    result = JSON.stringify(obj)
    result = JSON.parse(result)
  } else {
    result = obj
  }

  return result
}

export function getWeekOfYear() {
  var today = new Date()
  var firstDay = new Date(today.getFullYear(), 0, 1)
  var dayOfWeek = firstDay.getDay()
  var spendDay = 1
  if (dayOfWeek !== 0) {
    spendDay = 7 - dayOfWeek + 1
  }
  firstDay = new Date(today.getFullYear(), 0, 1 + spendDay)
  var d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000)
  var result = Math.ceil(d / 7)
  return result + 1
}
/**
 * @description 全埋点
 *  1.在所有methods方法中埋点为函数名
 *  2.在钩子函数中 (activated - created - mounted) 依次寻找这三个钩子
 *    如果存在就会增加埋点 VIEW
 *
 * 用法：
 *   @Buried
 *   在单文件导出对象一级子对象下;
 *   如果某方法不想设置埋点 可以 return 'noBuried' 即可
 */
export function Buried(target, funcName, descriptor) {
  const oriMethods = Object.assign({}, target.methods)
  const oriTarget = Object.assign({}, target)
  // methods方法中
  if (target.methods) {
    for (const name in target.methods) {
      target.methods[name] = function() {
        const result = oriMethods[name].call(this, ...arguments)
        // 如果方法中返回 noBuried 则不添加埋点
        if (typeof result === 'string' && result.includes('noBuried')) {
          console.log(name + '方法设置不添加埋点')
        } else if (result instanceof Promise) {
          result.then(res => {
            if (typeof res === 'string' && res.includes('noBuried')) { console.log(name + '方法设置不添加埋点'); return }
            console.log('添加埋点在methods方法中：', name.toUpperCase())
            this.$log(name)
          })
        } else {
          console.log('添加埋点在methods方法中：', name.toUpperCase())
          this.$log(name)
        }
        return result
      }
    }
  }
  // 钩子函数中
  const hookFun = (funName) => {
    target[funName] = function() {
      const result = oriTarget[funName].call(this, ...arguments)
      console.log('添加埋点，在钩子函数' + funName + '中：', 'VIEW')
      this.$log('VIEW')
      return result
    }
  }
  // 钩子函数中 view
  if (target.activated) {
    return hookFun('activated')
  } else if (target.created) {
    return hookFun('created')
  } else if (target.mounted) {
    return hookFun('mounted')
  }
}
// 所有支持的文件类型配置
export function heldFile(file) {
  const fileTypeList = ['doc', 'docx', 'xlsx', 'xls', 'ppt', 'pptx', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'mp4', 'avi', 'mov', 'mkv', 'pdf']
  const result = fileTypeList.filter(item => {
    return file.split('.')[1].toUpperCase() === item.toUpperCase()
  })
  console.log(result, 6666666666666666666666666666666666666)
  return result.length > 0
}
